import React, { useState, useEffect, useRef } from "react";
import * as echarts from "echarts";
import { LiveProvider, LiveEditor, LiveError, LivePreview } from "react-live";
import dracula from "prism-react-renderer/themes/dracula";

interface ReactEditorProps {
  code: string;
  onChange?: (code: string) => void;
  codeProps?: object;
  showEditor?: boolean;
}

export default function ReactEditor(props: ReactEditorProps) {
  const { code, onChange, codeProps = {}, showEditor = true } = props;

  const scope = { useState, useEffect, useRef, echarts, props: codeProps };

  const transformCode = (code: string) => {
    const regex = /\(.*?\)\s*=>/;

    const removedArgumentProps = code.replace(regex, "() => ");

    return removedArgumentProps;
  };

  return (
    <LiveProvider
      code={code}
      scope={scope}
      transformCode={transformCode}
      theme={dracula}
    >
      <div style={{ display: "flex" }}>
        <div style={{flex: "1 1 0px"}}>
          <LivePreview />
        </div>
        {showEditor && (
          <div style={{flex: "1 1 0px"}}>
            <LiveEditor onChange={onChange} />
          </div>
        )}
      </div>
      <LiveError />
    </LiveProvider>
  );
}
